package com.xhwl.logistics.service.impl.http;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.xhwl.common.exception.ApplicationException;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.utils.RSAUtils;
import com.xhwl.logistics.bo.VehicleCarportBO;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.constant.DaHuaIccConstant;
import com.xhwl.logistics.dto.http.*;
import com.xhwl.logistics.dto.http.query.DefinePeopleDaHuaDTO;
import com.xhwl.logistics.dto.http.query.QueryReserveSpaceDaHuaDTO;
import com.xhwl.logistics.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 车行对接大华ICC
 * @Author: hule
 * @Date: 2022/08/10
 */
@Slf4j
//@Service
public class DaHuaHttpServiceImpl {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 查询的每页最大数量
     */
    private static final int size = 500;

    private int pageNo = 1;

    /**
     * 道闸控制所用的参数
     */
    private static final String operateType="1";

    /**
     * 对接大华ICC，访客车预约取消
     */
    public ResultJson cancelCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, List<String> orderNos){
        JSONObject resultObject = postList(DaHuaIccConstant.VEHICLE_RESERVE_CAR_DELETE, orderNos, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("post path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_RESERVE_CAR_DELETE, JSON.toJSONString(orderNos), resultObject.getString("errMsg"));
            throw new BusinessException(""+resultObject.getString("errMsg"));
        }
        String dataStr = resultObject.getString("data");
        return ResultJson.success(dataStr);
    }

    /**
     * 对接大华ICC，访客车预约新增
     */
    public String reserveCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, QueryReserveSpaceDaHuaDTO queryReserveSpaceDaHuaDTO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("carNum", queryReserveSpaceDaHuaDTO.getCarNum());
        params.put("consumerName", queryReserveSpaceDaHuaDTO.getConsumerName());
        params.put("telNumber", queryReserveSpaceDaHuaDTO.getTelNumber());
        params.put("parkingLotCode", queryReserveSpaceDaHuaDTO.getParkingLotCode());
        params.put("sluiceChns", queryReserveSpaceDaHuaDTO.getSluiceChns());
        params.put("enterModel", queryReserveSpaceDaHuaDTO.getEnterModel());
        params.put("exitModel", queryReserveSpaceDaHuaDTO.getExitModel());
        params.put("reservationType", queryReserveSpaceDaHuaDTO.getReservationType());
        params.put("reservationCount", queryReserveSpaceDaHuaDTO.getReservationCount());
        params.put("startTimeStr", queryReserveSpaceDaHuaDTO.getStartTimeStr());
        params.put("endTimeStr", queryReserveSpaceDaHuaDTO.getEndTimeStr());
        params.put("memo", queryReserveSpaceDaHuaDTO.getMemo());
        JSONObject resultObject = post(DaHuaIccConstant.VEHICLE_RESERVE_CAR_ADD, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("post path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_RESERVE_CAR_ADD, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(""+resultObject.getString("errMsg"));
        }
        return resultObject.getString("data");
    }

    /**
     * 对接大华ICC，将未定义人员修改为定义人员
     */
    public ResultJson definePeople(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, List<DefinePeopleDaHuaDTO> definePeopleDaHuaDTOs){
        JSONObject resultObject = postList(DaHuaIccConstant.VEHICLE_DEFINE_PEOPLE, definePeopleDaHuaDTOs, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("post path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_DEFINE_PEOPLE, JSON.toJSONString(definePeopleDaHuaDTOs), resultObject.getString("errMsg"));
            throw new BusinessException(""+resultObject.getString("errMsg"));
        }
        String dataStr = resultObject.getString("data");
        return ResultJson.success(dataStr);
    }

    /**
     * 调用大华的接口，月卡缴费
     */
    public ResultJson chargeMonthCard(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, CardMonthChargeDaHuaDTO cardMonthChargeDaHuaDTO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("ownerId",cardMonthChargeDaHuaDTO.getOwnerId());
        params.put("owner",cardMonthChargeDaHuaDTO.getOwner());
        params.put("cardNumber",cardMonthChargeDaHuaDTO.getCardNumber());
        params.put("startTime",cardMonthChargeDaHuaDTO.getStartTime());
        params.put("endTime",cardMonthChargeDaHuaDTO.getEndTime());
        params.put("money",cardMonthChargeDaHuaDTO.getMoney());
        params.put("rechargeTimeStr",cardMonthChargeDaHuaDTO.getRechargeTimeStr());
        params.put("ownerTypeId",cardMonthChargeDaHuaDTO.getOwnerTypeId());
        params.put("ownerType",cardMonthChargeDaHuaDTO.getOwnerType());
        JSONObject resultObject = post(DaHuaIccConstant.VEHICLE_MONTH_CARD_CHARGE, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("post path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_MONTH_CARD_CHARGE, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(""+resultObject.getString("errMsg"));
        }
        String dataStr = resultObject.getString("data");
        return ResultJson.success(dataStr);
    }

    /**
     * 调用大华的接口，对道闸进行控制
     */
    public ResultJson controlDevice(VehicleIntegratedConfigBO vehicleIntegratedConfigBO,String channelId){
        HashMap<String, Object> params = new HashMap<>();
        params.put("channelId",channelId);
        params.put("operateType",operateType);
        JSONObject resultObject = post(DaHuaIccConstant.VEHICLE_DEVICE_CONTROL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("post path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_DEVICE_CONTROL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(""+resultObject.getString("errMsg"));
        }
        String dataStr = resultObject.getString("data");
        return ResultJson.success(dataStr);
    }

    /**
     * 查询车场的车位及余位信息
     */
    public VehicleCarportBO getDaHuaFreeCarSpot(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        HashMap<String, Object> params = new HashMap<>();
        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_CAR_SPOT_INFO, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("get path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_CAR_SPOT_INFO, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if(StringUtils.isEmpty(dataStr)){
            log.error("get path:{};params:{};data is null!", DaHuaIccConstant.VEHICLE_CAR_SPOT_INFO, JSON.toJSONString(params));
            return null;
        }
        JSONObject dataObject = JSONObject.parseObject(dataStr);
        VehicleCarportBO vehicleCarportBO = new VehicleCarportBO();
        vehicleCarportBO.setTotalNumber(Integer.parseInt(dataObject.getString("totalLot")));
        vehicleCarportBO.setFreeNumber(Integer.parseInt(dataObject.getString("idleLot")));
        return vehicleCarportBO;
    }

    /**
     * 调用大华接口，分页查询设备
     */
    public List<DeviceInfoDaHuaIccDTO> getDaHuaDevice(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum",pageNo);
        params.put("pageSize",size);
//        params.put("categorys",new Integer[]{DaHuaIccConstant.PEGE_DEVICE_TYPE});
//        params.put("unitTypes",new Integer[]{DaHuaIccConstant.PEGE_DEVICE_UNIT_TYPE});
        //获取所有的道闸设备,此编码从大华ICC平台接口文档中查出
        params.put("types", new String[]{DaHuaIccConstant.PEGE_ONE, DaHuaIccConstant.PEGE_TWO,
        DaHuaIccConstant.PEGE_THREE, DaHuaIccConstant.PEGE_FOUR, DaHuaIccConstant.PEGE_FIVE});
        JSONObject resultObject = post(DaHuaIccConstant.VEHICLE_DEVICE_INFO_PAGE, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("post path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_DEVICE_INFO_PAGE, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if (com.xhwl.common.utils.StringUtils.isEmpty(dataStr)) {
            log.error("post path:{};params:{};data is null!", DaHuaIccConstant.VEHICLE_DEVICE_INFO_PAGE, JSON.toJSONString(params));
            return null;
        }
        String pageDataStr = JSON.parseObject(dataStr).getString("pageData");
        if (com.xhwl.common.utils.StringUtils.isEmpty(pageDataStr)) {
            log.error("post path:{};params:{};pageData is null!", DaHuaIccConstant.VEHICLE_DEVICE_INFO_PAGE, JSON.toJSONString(params));
            return null;
        }
        List<DeviceInfoDaHuaIccDTO> deviceInfoDaHuaIccDTOS = this.handleData(pageDataStr);
        if (CollectionUtils.isEmpty(deviceInfoDaHuaIccDTOS)) {
            return null;
        }
        return deviceInfoDaHuaIccDTOS;
    }

    /**
     * 提取大华的设备信息
     * @param pageDataStr
     * @return
     */
    private List<DeviceInfoDaHuaIccDTO> handleData(String pageDataStr) {
        JSONArray arrayObject = JSONObject.parseArray(pageDataStr);
        List<DeviceInfoDaHuaIccDTO> deviceDaHuaDTOList = new ArrayList<>();
        arrayObject.forEach(object->{
            JSONObject dObject = JSON.parseObject(object.toString());
            JSONObject.parseArray(dObject.getString("units")).forEach(unit->{
                JSONObject unitObject = JSON.parseObject(unit.toString());
                if(com.xhwl.common.utils.StringUtils.equals(DaHuaIccConstant.PEGE_DEVICE_UNIT_TYPE.toString(),unitObject.getString("unitType"))){
                    JSONObject.parseArray(unitObject.getString("channels")).forEach(channel->{
                        JSONObject channelObject = JSON.parseObject(channel.toString());
                        DeviceInfoDaHuaIccDTO deviceDaHuaDTO = new DeviceInfoDaHuaIccDTO();
                        deviceDaHuaDTO.setDeviceIp(dObject.getString("deviceIp"));
                        deviceDaHuaDTO.setIsOnline(dObject.getString("isOnline"));
                        deviceDaHuaDTO.setChannelCode(channelObject.getString("channelCode"));
                        deviceDaHuaDTO.setChannelName(channelObject.getString("channelName"));
                        deviceDaHuaDTOList.add(deviceDaHuaDTO);
                    });
                }
            });
        });
        return deviceDaHuaDTOList;
    }

    /**
     * 调用大华接口，删除车辆
     */
    public ResultJson deleteCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO,String carId){
        Map<String, Object> params = new HashMap<>();
        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_CAR_DELETE + "/" + carId, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("get path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_OWNER_INFO_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        return ResultJson.success(dataStr);
    }

    /**
     * 获取人员和车辆信息
     */
    public OwnerCarInfoDaHuaIccDTO getDaHuaOwnerCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO,String ownerId){
        Map<String, Object> params = new HashMap<>();
        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_OWNER_INFO_URL + "/" + ownerId, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("get path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_OWNER_INFO_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if(StringUtils.isEmpty(dataStr)){
            log.error("get path:{};params:{};data is null;",DaHuaIccConstant.VEHICLE_OWNER_INFO_URL,JSON.toJSONString(params));
            return null;
        }
        return JSONObject.parseObject(dataStr,OwnerCarInfoDaHuaIccDTO.class);
    }

    /**
     * 调用大华接口，更新呢人员-车辆信息
     */
    public ResultJson updateOwnerCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO,OwnerCarInfoDaHuaIccDTO ownerCarInfoDaHuaIccDTO){
        Map<String, Object> params = new HashMap<>();
        params.put("ownerVO",ownerCarInfoDaHuaIccDTO.getOwnerVO());
        params.put("carVOList",ownerCarInfoDaHuaIccDTO.getCarVOList());
        JSONObject resultDataObject = post(DaHuaIccConstant.VEHICLE_OWNER_CAR_UPDATE_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if (resultDataObject == null) {
            return null;
        }
        if ("false".equals(resultDataObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VEHICLE_OWNER_CAR_UPDATE_URL, JSON.toJSONString(params), resultDataObject.getString("errMsg"));
            throw new BusinessException(""+resultDataObject.getString("errMsg"));
        }
        String idStr = resultDataObject.getString("data");
        return ResultJson.success(idStr);
    }

    /**
     * 调用大华接口，新增人员-车辆信息
     */
    public ResultJson addOwnerCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO,OwnerCarInfoDaHuaIccDTO ownerCarInfoDaHuaIccDTO){
        Map<String, Object> params = new HashMap<>();
        params.put("ownerVO",ownerCarInfoDaHuaIccDTO.getOwnerVO());
        params.put("carVOList",ownerCarInfoDaHuaIccDTO.getCarVOList());
        JSONObject resultDataObject = post(DaHuaIccConstant.VEHICLE_OWNER_CAR_ADD_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if (resultDataObject == null) {
            return null;
        }
        if ("false".equals(resultDataObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VEHICLE_OWNER_CAR_ADD_URL, JSON.toJSONString(params), resultDataObject.getString("errMsg"));
            throw new BusinessException(""+resultDataObject.getString("errMsg"));
        }
        String idStr = resultDataObject.getString("data");
        return ResultJson.success(idStr);
    }

    /**
     * 调用大华接口，根据人员id查询人员的信息
     */
    public OwnerInfoDaHuaDTO getDaHuaOwner(VehicleIntegratedConfigBO vehicleIntegratedConfigBO,String ownerId){
        Map<String, Object> params = new HashMap<>();
        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_OWNER_INFO_URL + "/" + ownerId, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject == null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("get path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_OWNER_INFO_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if(StringUtils.isEmpty(dataStr)){
            log.error("get path:{};params:{};data is null;",DaHuaIccConstant.VEHICLE_OWNER_INFO_URL,JSON.toJSONString(params));
            return null;
        }
        JSONObject dataObject = JSONObject.parseObject(dataStr);
        String ownerVOStr = dataObject.getString("ownerVO");
        if(StringUtils.isEmpty(ownerVOStr)){
            log.error("get path:{};params:{};ownerVOStr is null;",DaHuaIccConstant.VEHICLE_OWNER_INFO_URL,JSON.toJSONString(params));
            return null;
        }
        return JSONObject.parseObject(ownerVOStr, OwnerInfoDaHuaDTO.class);
    }

    /**
     * 调用大华接口，获取所有区域下的车辆列表信息
     */
    public List<CarInfoDaHuaDTO> getDaHuaCarList(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        Map<String, Object> params = new HashMap<>();
        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_CAR_LIST_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if(resultObject ==null){
            return null;
        }
        if("false".equals(resultObject.getString("success"))){
            log.error("get path:{};params:{};errMsg:{}",DaHuaIccConstant.VEHICLE_CAR_LIST_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if(StringUtils.isEmpty(dataStr)){
            log.error("get path:{};params:{};data is null;",DaHuaIccConstant.VEHICLE_CAR_LIST_URL,JSON.toJSONString(params));
            return null;
        }
        JSONObject dataObject = JSONObject.parseObject(dataStr);
        String pageData = dataObject.getString("pageData");
        if(StringUtils.isEmpty(pageData)){
            log.error("get path:{};params:{};pageData is null;",DaHuaIccConstant.VEHICLE_CAR_LIST_URL,JSON.toJSONString(params));
            return null;
        }
        List<CarInfoDaHuaDTO> carInfoDaHuaDTOS = JSONObject.parseArray(pageData, CarInfoDaHuaDTO.class);
        if(CollectionUtils.isEmpty(carInfoDaHuaDTOS)){
            return null;
        }
        return carInfoDaHuaDTOS;
    }

    /**
     * 调用大华接口，获取停车场（区域）基本信息列表
     * @param vehicleIntegratedConfigBO
     * @return
     */
    public List<ParkingLotAreaInfoDaHuaDTO> getParkingLotAreaInfo(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        HashMap<String, Object> params = new HashMap<>();
        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_LOT_INFO_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(), 
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if (resultObject == null) {
            return null;
        }
        if ("false".equals(resultObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VEHICLE_LOT_INFO_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if (StringUtils.isEmpty(dataStr)) {
            log.error("post path:{};params:{};data is null!", DaHuaIccConstant.VEHICLE_LOT_INFO_URL, JSON.toJSONString(params));
            return null;
        }
        List<ParkingLotAreaInfoDaHuaDTO> parkingLotAreaInfoDaHuaDTOS = JSONObject.parseArray(dataStr, ParkingLotAreaInfoDaHuaDTO.class);
        if (CollectionUtils.isEmpty(parkingLotAreaInfoDaHuaDTOS)) {
            return null;
        }
        return parkingLotAreaInfoDaHuaDTOS;
    }

    /**
     * 调用大华接口，获取通道及设备信息
     * @param vehicleIntegratedConfigBO
     * @return
     */
    public List<PassageAndDeviceDaHuaDTO> getPassageAndDeviceList(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, String parkingLotId){
        HashMap<String, Object> params = new HashMap<>();
        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_PASSAGE_DEVICE_URL + "/" + parkingLotId, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if (resultObject == null) {
            return null;
        }
        if ("false".equals(resultObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VEHICLE_PASSAGE_DEVICE_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if (StringUtils.isEmpty(dataStr)) {
            log.error("post path:{};params:{};data is null!", DaHuaIccConstant.VEHICLE_PASSAGE_DEVICE_URL, JSON.toJSONString(params));
            return null;
        }
        List<PassageAndDeviceDaHuaDTO> passageAndDeviceDaHuaDTOS = JSONObject.parseArray(dataStr, PassageAndDeviceDaHuaDTO.class);
        if (CollectionUtils.isEmpty(passageAndDeviceDaHuaDTOS)) {
            return null;
        }
        return passageAndDeviceDaHuaDTOS;
    }

    /**
     * 调用大华接口，获取停车场用户类别(卡类型)列表
     * @param vehicleIntegratedConfigBO
     * @return
     */
    public List<CardTypeDaHuaDTO> getCardType(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        HashMap<String, Object> params = new HashMap<>();
        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_CARD_TYPE_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if (resultObject == null) {
            return null;
        }
        if ("false".equals(resultObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VEHICLE_CARD_TYPE_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if (StringUtils.isEmpty(dataStr)) {
            log.error("post path:{};params:{};data is null!", DaHuaIccConstant.VEHICLE_CARD_TYPE_URL, JSON.toJSONString(params));
            return null;
        }
        List<CardTypeDaHuaDTO> cardTypeDaHuaDTOS = JSONObject.parseArray(dataStr, CardTypeDaHuaDTO.class);
        if (CollectionUtils.isEmpty(cardTypeDaHuaDTOS)) {
            return null;
        }
        return cardTypeDaHuaDTOS;
    }

    /**
     * 获取车场统计基本数据
     * @param vehicleIntegratedConfigBO
     * @return
     */
    public CarSpotStatDaHuaDTO getCarSpotStat(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        HashMap<String, Object> params = new HashMap<>();
        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_CAR_TOTAL_NUM_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if (resultObject == null) {
            return null;
        }
        if ("false".equals(resultObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VEHICLE_CAR_TOTAL_NUM_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if (StringUtils.isEmpty(dataStr)) {
            log.error("post path:{};params:{};data is null!", DaHuaIccConstant.VEHICLE_CAR_TOTAL_NUM_URL, JSON.toJSONString(params));
            return null;
        }
        return JSONObject.parseObject(dataStr, CarSpotStatDaHuaDTO.class);
    }

    /**
     * 分页查询大华的车辆列表
     */
    private List<VehicleCarDaHuaIccDTO> pullCarPage(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, int pageNum, int pageSize){
        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);

        JSONObject resultObject = get(DaHuaIccConstant.VEHICLE_CAR_LIST_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(), 
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if (resultObject == null) {
            return null;
        }
        if ("false".equals(resultObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VEHICLE_CAR_LIST_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        String pageDataStr = JSON.parseObject(dataStr).getString("pageData");
        String pageNoStr = JSON.parseObject(dataStr).getString("totalPage");
        pageNo = Integer.parseInt(pageNoStr);
        if (StringUtils.isEmpty(pageDataStr)) {
            log.error("post path:{};params:{};data is null!", DaHuaIccConstant.VEHICLE_CAR_LIST_URL, JSON.toJSONString(params));
            return null;
        }
        List<VehicleCarDaHuaIccDTO> carDaHuaIccDTOS = JSONObject.parseArray(pageDataStr, VehicleCarDaHuaIccDTO.class);
        if (CollectionUtils.isEmpty(carDaHuaIccDTOS)) {
            return null;
        }
        return carDaHuaIccDTOS;
    }

    /**
     * 查询车辆总数
     * @Deprecated 2022/08/11 接口调不通，直接用分页接口去查询，设置总数
     * @param vehicleIntegratedConfigBO
     * @return
     */
    private Integer pullCarTotalNum(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        HashMap<String, Object> params = new HashMap<>();

        JSONObject resultObject = post(DaHuaIccConstant.VEHICLE_CAR_NUM_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(), 
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if (resultObject == null) {
            return null;
        }
        if ("false".equals(resultObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VEHICLE_CAR_NUM_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");

        return Integer.parseInt(dataStr);
    }

    /**
     * 全量查询大华的车辆列表信息
     * @param vehicleIntegratedConfigBO
     * @return
     */
    public ResultJson pullCarList(VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
//        Integer carTotalNum = pullCarTotalNum(configDTO);
        List<VehicleCarDaHuaIccDTO> carDaHuaIccDTOS = new ArrayList<>();
        for (int i = 1; i < (pageNo / size) + 2; i++){
            List<VehicleCarDaHuaIccDTO> carDaHuaIccDTOList = pullCarPage(vehicleIntegratedConfigBO, i, size);
            carDaHuaIccDTOS.addAll(carDaHuaIccDTOList);
        }
        log.info(carDaHuaIccDTOS.toString());
        return ResultJson.success(carDaHuaIccDTOS);
    }

    /**
     * 新增车辆
     * TODO 车主id怎么传递？
     * @return
     */
    public ResultJson addCar(VehicleIntegratedConfigBO vehicleIntegratedConfigBO, VehicleCarDaHuaIccDTO vehicleCarDaHuaIccDTO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("carColor", vehicleCarDaHuaIccDTO.getCarColor());
        params.put("carType", vehicleCarDaHuaIccDTO.getCarType());
        params.put("carBrand", vehicleCarDaHuaIccDTO.getCarBrand());
        params.put("carNumColor", vehicleCarDaHuaIccDTO.getCarNumColor());
        params.put("deptId", vehicleCarDaHuaIccDTO.getDeptId());
        params.put("carNum", vehicleCarDaHuaIccDTO.getCarNum());
        params.put("ownerId", vehicleCarDaHuaIccDTO.getOwnerId());
        params.put("parkType", vehicleCarDaHuaIccDTO.getParkType());
        params.put("parkinglotCode", vehicleCarDaHuaIccDTO.getParkinglotCode());

        JSONObject resultObject = post(DaHuaIccConstant.VEHICLE_CAR_ADD_URL, params, vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(), 
                vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProductId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getUser(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getPassword(),
                vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppId(), vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getAppSecret());
        if (resultObject == null) {
            return null;
        }
        if ("false".equals(resultObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VEHICLE_CAR_ADD_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String idStr = resultObject.getString("data");
        return ResultJson.success(idStr);
    }

    public SecurityDaHuaDTO getToken(Integer projectId, Integer productId, String ipAndPort, String loginName, String password, String clientId, String clientSecret) {
        ReentrantLock lock = new ReentrantLock();
        SecurityDaHuaDTO securityDaHuaDTO = null;
        lock.lock();
        try {
            String key = new StringBuffer(DaHuaIccConstant.SUPPLIER_SYSTEM_TOKEN).append("-").append("logistics").append("-").append(projectId).append("-").append(productId).toString();
            Object value = redisUtils.get(key);
            if (value == null) {
                String publicKey = this.getPublicKey(ipAndPort);
                securityDaHuaDTO = this.login(ipAndPort, loginName, password,  publicKey, clientId, clientSecret);
                redisUtils.setWithMinute(key, JSONObject.toJSONString(securityDaHuaDTO), 4);
            } else {
                securityDaHuaDTO = JSON.parseObject((String) value, SecurityDaHuaDTO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return securityDaHuaDTO;
    }

    private String getPublicKey(String ipAndPort) {
        JSONObject resultObject = this.get(ipAndPort + DaHuaIccConstant.PUBLIC_KEY_URL);
        if ("false".equals(resultObject.getString("success"))) {
            log.error("【DahuaICC getPublicKey】path:{};errMsg:{}", DaHuaIccConstant.PUBLIC_KEY_URL, resultObject.getString("errMsg"));
            throw new BusinessException("DahuaICC getPublicKey failed!");
        }
        JSONObject data = JSON.parseObject(resultObject.getString("data"));
        return data.getString("publicKey");
    }

    private SecurityDaHuaDTO login(String ipAndPort, String loginName, String password, String publicKey, String clientId, String clientSecret) {
        Map<String, Object> params = new HashMap();
        params.put("grant_type", "password");
        params.put("username", loginName);
        params.put("password",  RSAUtils.encrypt(password,publicKey));
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        params.put("public_key", publicKey);
        JSONObject resultObject = this.post(ipAndPort + DaHuaIccConstant.LOGIN_URL, params);
        if ("false".equals(resultObject.getString("success"))) {
            log.error("【DahuaICC login】path:{};params:{};errMsg:{}", DaHuaIccConstant.LOGIN_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException("DahuaICC login failed!");
        }
        String dataStr = resultObject.getString("data");
        SecurityDaHuaDTO securityDaHuaDTO = SecurityDaHuaDTO.builder()
                .userId(JSONObject.parseObject(dataStr).getString("userId"))
                .userName(loginName)
                .token(JSONObject.parseObject(dataStr).getString("access_token")).build();
        return securityDaHuaDTO;
    }

    private JSONObject post(String path, Map<String, Object> params) {
        log.info("【DahuaICC post】path:{};params:{}", path, JSON.toJSONString(params));
        String result = null;
        try {
//            Map<String, String> header = new HashMap<>();
//            header.put(DaHuaIccConstant.AUTHOR, DaHuaIccConstant.AUTHOR_VALUE);
            result = HttpRequest
                    .post(path)
//                    .addHeaders(header)
                    .body(JSON.toJSONString(params))
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【DahuaICC post】path:{};params:{}; request failed!", path, JSON.toJSONString(params));
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【DahuaICC post】path:{};params:{};result is null!", path, JSON.toJSONString(params));
            throw new BusinessException();
        }
        log.info("【DahuaICC post】path:{};params:{};result:{}", path, JSON.toJSONString(params), result);
        return JSON.parseObject(result);
    }

    public JSONObject post(String api, Map<String, Object> params, Integer projectId, Integer productId, String ipAndPort, String loginName, String password, String appId, String appSecret) {
        SecurityDaHuaDTO securityDaHuaDTO = this.getToken(projectId, productId, ipAndPort, loginName, password, appId, appSecret);
        if (securityDaHuaDTO == null) {
            log.error("【DahuaICC post】path:{};getToken fail!", api);
            return null;
        }
        log.warn(securityDaHuaDTO.getToken());
        StringBuffer pathBuffer = new StringBuffer()
                .append(ipAndPort)
                .append(api)
                .append("?userId=")
                .append(securityDaHuaDTO.getUserId())
                .append("&userName=")
                .append(securityDaHuaDTO.getUserName())
                .append("&token=")
                .append(securityDaHuaDTO.getToken());
        return this.postWithAuth(pathBuffer.toString(), params, securityDaHuaDTO);
    }

    private JSONObject postWithAuth(String path, Map<String, Object> params, SecurityDaHuaDTO securityDaHuaDTO) {
        log.info("【DahuaICC post】path:{};params:{}", path, JSON.toJSONString(params));
        String result = null;
        try {
            Map<String, String> header = new HashMap<>();
            header.put(DaHuaIccConstant.AUTHOR, "bearer " + securityDaHuaDTO.getToken());
            result = HttpRequest
                    .post(path)
                    .addHeaders(header)
                    .body(JSON.toJSONString(params))
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【DahuaICC post】path:{};params:{}; request failed!", path, JSON.toJSONString(params));
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【DahuaICC post】path:{};params:{};result is null!", path, JSON.toJSONString(params));
            throw new BusinessException();
        }
        log.info("【DahuaICC post】path:{};params:{};result:{}", path, JSON.toJSONString(params), result);
        return JSON.parseObject(result);
    }

    /**
     * 添加满足参数是List的情况
     */
    public JSONObject postList(String api, List params, Integer projectId, Integer productId, String ipAndPort, String loginName, String password, String appId, String appSecret) {
        SecurityDaHuaDTO securityDaHuaDTO = this.getToken(projectId, productId, ipAndPort, loginName, password, appId, appSecret);
        if (securityDaHuaDTO == null) {
            log.error("【DahuaICC post】path:{};getToken fail!", api);
            return null;
        }
        log.warn(securityDaHuaDTO.getToken());
        StringBuffer pathBuffer = new StringBuffer()
                .append(ipAndPort)
                .append(api)
                .append("?userId=")
                .append(securityDaHuaDTO.getUserId())
                .append("&userName=")
                .append(securityDaHuaDTO.getUserName())
                .append("&token=")
                .append(securityDaHuaDTO.getToken());
        return this.postWithAuth(pathBuffer.toString(), params, securityDaHuaDTO);
    }

    /**
     * 添加满足参数是List的情况
     */
    private JSONObject postWithAuth(String path, List params, SecurityDaHuaDTO securityDaHuaDTO) {
        log.info("【DahuaICC post】path:{};params:{}", path, JSON.toJSONString(params));
        String result = null;
        try {
            Map<String, String> header = new HashMap<>();
            header.put(DaHuaIccConstant.AUTHOR, "bearer " + securityDaHuaDTO.getToken());
            result = HttpRequest
                    .post(path)
                    .addHeaders(header)
                    .body(JSON.toJSONString(params))
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【DahuaICC post】path:{};params:{}; request failed!", path, JSON.toJSONString(params));
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【DahuaICC post】path:{};params:{};result is null!", path, JSON.toJSONString(params));
            throw new BusinessException();
        }
        log.info("【DahuaICC post】path:{};params:{};result:{}", path, JSON.toJSONString(params), result);
        return JSON.parseObject(result);
    }

    private JSONObject get(String path) {
        String result = null;
        try {
//            Map<String, String> header = new HashMap<>();
//            header.put(DaHuaIccConstant.AUTHOR, DaHuaIccConstant.AUTHOR_VALUE);
            result = HttpRequest.get(path).execute().body();
        } catch (HttpException e) {
            log.error("【DahuaICC get】path:{}; request failed!", path);
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【DahuaICC get】path:{};result is null!", path);
            throw new BusinessException();
        }
        log.info("【DahuaICC get】path:{};result:{}", path, result);
        return JSON.parseObject(result);
    }

    public JSONObject get(String api, Map<String, Object> params, Integer projectId, Integer productId, String ipAndPort, String loginName, String password, String clientId, String clientSecret) {
        SecurityDaHuaDTO securityDaHuaDTO = this.getToken(projectId, productId, ipAndPort, loginName, password, clientId, clientSecret);
        if (securityDaHuaDTO == null) {
            log.error("【DahuaICC post】path:{};getToken fail!", api);
            return null;
        }
        StringBuffer pathBuffer = new StringBuffer()
                .append(ipAndPort)
                .append(api)
                .append("?userId=")
                .append(securityDaHuaDTO.getUserId())
                .append("&userName=")
                .append(securityDaHuaDTO.getUserName())
                .append("&token=")
                .append(securityDaHuaDTO.getToken());
        return this.getWithAuth(pathBuffer.toString(), securityDaHuaDTO);
    }

    private JSONObject getWithAuth(String path, SecurityDaHuaDTO securityDaHuaDTO) {
        String result = null;
        try {
            Map<String, String> header = new HashMap<>();
            header.put(DaHuaIccConstant.AUTHOR, "bearer " + securityDaHuaDTO.getToken());
            result = HttpRequest.get(path).addHeaders(header).execute().body();
        } catch (HttpException e) {
            log.error("【DahuaICC get】path:{}; request failed!", path);
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【DahuaICC get】path:{};result is null!", path);
            throw new BusinessException();
        }
        log.info("【DahuaICC get】path:{};result:{}", path, result);
        return JSON.parseObject(result);
    }

    public static String generateOpenCode(Integer accountId,Integer projectId){
        return accountId+"by"+projectId;
    }


}
